//
//  ZJUserCenter.m
//  MoreStarLiveTelecast
//
//  Created by babbage on 16/8/23.
//  Copyright © 2016年 babbage. All rights reserved.
//

#import "ZJUserCenter.h"

//static NSString *const kZJUserCenterLoginUserDir = @"LoginUserDir";
//static NSString *const kZJUserCenterLastLoginUserUDF = @"kZJUserCenterLastLoginUserUDF";
#define kZJUserCenterLoginUserDir @"LoginUserDir"
#define kZJUserCenterLastLoginUserUDF @"kZJUserCenterLastLoginUserUDF"

@implementation ZJUserCenter

+ (ZJUserCenter *)shareCenter
{
    static ZJUserCenter *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        if (!_instance) {
            _instance = [[self alloc]init];
        }
    });
    
    return _instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        
        [self readLastLoginUser];
    }
    return self;
}
- (void)readLastLoginUser
{
    NSString *userId = GJCFUDFGetValue(kZJUserCenterLastLoginUserUDF);
    
    if (GJCFStringIsNull(userId)) {
        return;
    }
    
    NSData *userData = [NSData dataWithContentsOfFile:[self userSavePath:userId]];
    
    NSDictionary *userInfo = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    
    self.innerLoginUser = [[ZJUserModel alloc]initWithDictionary:userInfo error:nil];
}
- (NSString *)userSavePath:(NSString *)userId
{
    NSString *cacheDir = GJCFAppCachePath(kZJUserCenterLoginUserDir);
    if (!GJCFFileDirectoryIsExist(cacheDir)) {
        GJCFFileDirectoryCreate(cacheDir);
    }
    
    return [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.md5",userId]];
}
#pragma mark --- 保存信息 ---
-(void)LoginUserWithType:(NSString *)type withUsid:(NSString *)usid withIconImg:(NSString *)img withNickName:(NSString *)nickName withSuccess:(ZJUserCenterRequestSuccessBlock)success withFaild:(ZJUserCenterRequestFaildBlock)fail
{
    NSDictionary *param = @{@"type":type,@"usid":usid,@"nickname":nickName,@"img":img};
    [StarHttpTool post:ThirdLoginURL params:param success:^(id responseObj) {
        MJRefreshLog(@"%@",responseObj);
        if (![[responseObj objectForKey:@"state"] integerValue]) {
            if (!self.innerLoginUser) {
                self.innerLoginUser = [[ZJUserModel alloc] init];
                self.innerLoginUser.user_type = type;
                self.innerLoginUser.user_name = nickName;
                self.innerLoginUser.user_icon_url = img;
                self.innerLoginUser.user_sex = @"0";
            }
            //后台返回的数据处理
            NSDictionary *result = [responseObj objectForKey:@"result"];
            //登录成功后保存用户信息
            //用户id
            if (!GJCFStringIsNull([result objectForKey:@"u_idt"])) {
                self.innerLoginUser.user_id = [result objectForKey:@"u_id"];
            }
            //角色
            if (!GJCFStringIsNull([result objectForKey:@"u_idt"])) {
                self.innerLoginUser.user_role = [result objectForKey:@"u_idt"];
            }
            //头像处理
            if (!GJCFStringIsNull([result objectForKey:@"u_img"])) {
                self.innerLoginUser.user_icon_url = [result objectForKey:@"u_img"];
            }
            //保存对象
            [self saveCurrentLoginUser];
            success(@"succeed");
        }else{
            success([responseObj objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        if (error) {
            fail(error);
        }
    }];
}
-(void)saveCurrentLoginUser
{
    if (!self.innerLoginUser) {
        return;
    }
    
    NSDictionary *userInfo = [self.innerLoginUser toDictionary];
    
    NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:userInfo];
    
    [userData writeToFile:[self userSavePath:self.innerLoginUser.user_id] atomically:YES];
    
    GJCFUDFCache(kZJUserCenterLastLoginUserUDF, self.innerLoginUser.user_id);
}

#pragma mark --- 其他方法 ---
- (BOOL)isLogin
{
    return self.innerLoginUser? YES:NO;
}
- (ZJUserModel *)currentLoginUser
{
    return self.innerLoginUser;
}
- (void)updateNickname:(NSString *)nickname
{
    if (GJCFStringIsNull(nickname)) {
        return;
    }
    
    self.innerLoginUser.user_nickName = nickname;
    
    [self saveCurrentLoginUser];
}
- (void)updateAvatar:(NSString *)imageUrl
{
    if (GJCFStringIsNull(imageUrl)) {
        return;
    }
    
    self.innerLoginUser.user_icon_url = imageUrl;
    
    [self saveCurrentLoginUser];
}
-(void)UserExitLogin;
{
    [self deleteUser];
}
- (void)deleteUser
{
    if (!self.innerLoginUser) {
        return;
    }
    self.innerLoginUser = nil;
    GJCFUDFRemove(kZJUserCenterLastLoginUserUDF);
}

@end
